package com.northpool.operator.platform;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.utils.StpOperatorHelper;

@OperatorInfo(ref = "UserLoginOperator", name = "平台登录信息")
@OutputParams({
        @OutputParam(ref = "userId", name = "用户ID"),
        @OutputParam(ref = "token", name = "用户TOKEN"),
        @OutputParam(ref = "no", name = "网关令牌"),
})
public class UserLoginOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "url", name = "平台地址", desc = "平台服务地址，如: http://10.21.164.45:8021", required = true),
            @InputParam(ref = "username", name = "用户名", desc = "平台用户名", required = true),
            @InputParam(ref = "password", name = "密码", desc = "国密加密后的密钥串", required = true)
    })
    public UserLoginOperator() {

    }

    public static void main(String[] args) throws Exception {
        OperatorTestBuild.execute(UserLoginOperator.class, TestParamBuilder.aBuilder()
                        .param("url", "http://192.168.164.45:8021")
                        .param("username", "xxzxadmin")
                        .param("password", "fhwpC4gOP3scozAbRIzZDQ==")
                .build());
    }

    @Override
    public void execute(ParamTool params) throws Exception {
        String platformUrl = params.getStr("url");
        String username = params.getStr("username");
        String password = params.getStr("password");
        // 使用国密加密
//        password = SM4.encryptData_ECB(password);

        String userLoginUrl = StrUtil.format("{}/datahub/usercenter/userinfo/userLogin", platformUrl);
        //{"username":"xxzxadmin","password":"fhwpC4gOP3scozAbRIzZDQ=="}
        JSONObject requestBody = new JSONObject();
        requestBody.put("username", username);
        requestBody.put("password", password);

        try (HttpResponse execute = HttpUtil.createPost(userLoginUrl)
                .body(requestBody.toJSONString())
                .setConnectionTimeout(3000)
                .setReadTimeout(3000)
                .timeout(6000)
                .execute()
        ) {
            if (execute.getStatus() != 200) {
                throw new RuntimeException("用户中心服务异常,返回状态码：" + execute.getStatus());
            }
            String body = execute.body();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Integer statusCode = jsonObject.getInteger("statusCode");
            if (statusCode.equals(401)) {
                throw new RuntimeException("用户未登录");
            } else if (!statusCode.equals(200)) {
                throw new RuntimeException("用户信息获取异常：" + body);
            }
            // 200 OK
            JSONObject data = jsonObject.getJSONObject("data");
            String token = execute.header("token");
            String no = execute.header("no");
            this.result("token", token);
            this.result("no", no);
            this.result("userId", data.getString("id"));
        } catch (Exception e) {
            String message = ExceptionUtil.getMessage(e);
            this.error(message);
        }
    }
}
